<template>
  <div id="PatternClassDlg">
    <el-dialog v-model="drawerVisible" @close="handleClose" title="图形分类器维护" width="30%" height="480px" draggable>
      <el-header height="40px" style="display: flex;align-items: center;justify-content: left;width: 98%;">
            <el-button class="classbutton" @click="onNewFirst">新建第一级</el-button>
        </el-header>
      <el-container style="height:470px">
        <el-main v-if="disType == 'full'" style="height:470px">
          <div class="scrollDiv">
            <el-tree :data="CategoryList" :key="treeKey" show-checkbox node-key="id" :default-expanded-keys="['1']"
              :default-checked-keys="checkedKeyArr" :props="defaultProps" :render-content="renderContent"
              @check="onCheckNode" @node-click="onClickNode" style="height:470px">
            </el-tree>
          </div>


        </el-main>

      </el-container>
      <template #footer>
        <span class="dialog-footer" >
          <el-button class="classbutton" style="margin-top: 68px;" type="primary" @click="drawerVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// import axios from 'axios';
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex';
import { ElMessageBox,ElMessage } from 'element-plus';
// import {v4 as uuidv4} from 'uuid';
const store = useStore();
const parentModule = ref(null)
const disType = ref("full")
const treeKey = ref(0);

var drawerVisible = ref(false)

const checkedKeyArr = ref([])
const preCheckedNodeArr = ref([])
var CategoryList = [];

const defaultProps = {
  children: 'children',
  label: 'title',
}

onMounted(() => {
  //initAllCategory();
})


var handleClose = function(){
  //initAllCategory();
}

//checkedNodes,checkedKeys,halfCheckedNodes,halfCheckedKeys
var onCheckNode = function (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) {
  console.log(checkedKeys);
  let selNodeArr = checkedKeys.checkedNodes;
  //window.ToolCollapsePanel.value.notifySelNode(selNodeArr);
  checkedKeyArr.value = [];
  for (let i = 0; i < selNodeArr.length; i++) {
    let t = selNodeArr[i];
    checkedKeyArr.value.push(t.id);
  }
}

var onNewFirst = function(){
  createNewNode(null,null);
}

var createNewNode = function(node,nodedata){
  if(checkLogin()){
    ElMessageBox.prompt('请输入新分类信息', '新增', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(({ value }) => {
        if (value != null) {
          const newid = uuidv4();
          var pid;
          if(nodedata !== null){
            pid = nodedata.id;
          }else{
            pid = "root";
          }
          let category = {
                id: newid,
                name: value,
                title: value,
                pid: pid,
                userid:store.state.uid
            };

            var url = "api/toolcategory/add";
            axios.post(url, category).then(res => {
              console.log(res.data);
              if("success" === res.data.status){
                  //initDatas(res.data);
                const newChild = { id: newid,pid:pid, name:value,title: value,userid:store.state.uid, children: [] };
                if(nodedata !== null){
                  if (!nodedata.children) {
                    nodedata.children = []
                  }
                  nodedata.children.push(newChild);
                  node.expand();
                }else{
                  CategoryList.push(newChild);
                  treeKey.value++;
                }
              }else{
                ElMessage(res.data.message);
                return;
              }
            }).catch(function (error) {
              ElMessage('新增分类出错:'+error);
              return;
            })
        }
    }).catch(() => { });
  }
}

var onClickNode = function (item) {
  console.log("container tree click");
  console.log(item);
  let className = item.className;
  console.log(className);
  /* var url = "api/symbol/getSymbolByClass";
  var postObj = { "category": className, "userid": "longx13" };
  post2GetCurentSelClassSymbol(url, postObj); */
}

const post2GetCurentSelClassSymbol = function (url, obj) {
  axios.post(url, obj).then(res => {
    console.log(res.data);
    initToolBox(res.data);
  }).catch(function (error) {
    console.log(error);
  })
}

var parseChild = function (list) {
  let childArr = [];
  for (let i = 0; i < list.length; i++) {
    let t = list[i];
    let className = t.name;
    let title = t.title;
    let id = t.id;
    let isleaf = true;
    let children = [];
    if (t.children != null) {
      isleaf = false;
      children = parseChild(t.children);
    }
    let info = { id, title, className, isleaf, children };
    childArr.push(info);
    setToChkedKeyArr(id, className);
  }
  return childArr;
}

var initDatas = function (list) {
  CategoryList.value = [];
  let tmpArr = [];
  for (let i = 0; i < list.length; i++) {
    let t = list[i];
    let className = t.name;
    let title = t.title;
    let id = t.id;
    let isleaf = true;
    let children = [];
    if (t.children != null) {
      isleaf = false;
      children = parseChild(t.children);
    }
    let info = { id, title, className, isleaf, children };
    tmpArr.push(info);

    setToChkedKeyArr(id, className);
  }
  CategoryList.value = tmpArr;
}

const setToChkedKeyArr = (id, className) => {
  let inPreChkArr = false;
  let preList = preCheckedNodeArr.value;
  preList.forEach(ele => {
    if (ele.name == className) {
      inPreChkArr = true;
      return;
    }
  });

  if (inPreChkArr) {
    let inChkKeyArr = false;
    checkedKeyArr.value.forEach(ele => {
      if (ele.id == id) {
        inChkKeyArr = true;
        return;
      }
    });
    if (!inChkKeyArr) {
      checkedKeyArr.value.push(id);
    }
  }

}

async function post2GetAllCategory(url, obj) {
  const response = await axios.post(url,obj);
    CategoryList = response.data;
    treeKey.value++;
   /* axios.post(url, obj).then(res => {
    console.log(res.data);
    //initDatas(res.data);
    data = res.data;
    CategoryList = data;
    treeKey.value++;
  }).catch(function (error) {
    console.log(error);
  }) */
}

async function fetchData(url, obj){
  const response = await axios.post(url,obj);
  return response.data;
}

var initAllCategory = function () {
  console.log("initAllCategory********************************");
  var url = "api/toolcategory/getAllAsTree";
  var userid = store.state.uid;
  if(!userid || '' === userid){
    userid = "system";
  }
  var postObj = { "userid": userid };
  post2GetAllCategory(url, postObj)
}

var initToolBox = function (list) {
  toolList_data.value = [];
  var toolArr = [];
  for (var m = 0; m < list.length; m++) {
    var t = list[m];
    var id = t.type;
    var name = t.name;
    var iconURL = t.iconURL;
    var category = t.category;
    var yuansu = { id, name, iconURL, category };
    toolArr.push(yuansu);
  }
  toolList_data.value = toolArr;
}

const setPreCheckedNodeArr = (arr) => {
  preCheckedNodeArr.value = arr;
}

function renderContent(h, { node, data, store }) {
  return h(
    "div",
    {
      class: "custom-tree-node",
      style: { width: '100%', display: "flex", justifyContent: "space-between" } // 设置父元素的样式
    },
    [
      h(
        "span",
        {
          class: "node-label",
          style: { flex: "1" } // 设置节点名称的样式，使其占据剩余空间
        },
        node.data.title
      ),
      h(
        "div",
        { class: "action-links" },
        [
          h(
            "a",
            {
              onClick: () => append(node,data),
              style: { marginLeft: "50px", color: "#3c92fc" }, // 设置添加按钮的样式，设置左边距
              class:"el-icon-plus"
            },
            " 添加 "
          ),
          h(
            "a",
            {
              onClick: () => edit(data),
              style: { marginLeft: "10px", color: "#3c92fc" }, // 设置编辑按钮的样式，设置左边距
              class:"el-icon-edit"
            },
            " 编辑 "
          ),
          h(
            "a",
            {
              onClick: () => remove(node, data, store),
              style: { marginLeft: "10px", color: "#fd181d" }, // 设置删除按钮的样式，设置左边距
              class:"el-icon-delete"
            },
            " 删除 "
          ),

        ]
      )
    ]
  );
}

function checkLogin(){
  if(null === store.state.uid || '' === store.state.uid){
    ElMessage('请先登录后再执行该操作');
    return false;
  }else{
    return true;
  }
}

// 添加
function append(node,data) {
  createNewNode(node,data);
}
 
// 删除
function remove(node, data) {
  if(checkLogin()){
    if("system" === data.userid){
      ElMessage('系统预置分类，不允许删除');
      return;
    }
    if(data.userid !== store.state.uid){
      ElMessage('非本账户创建的分类，不允许删除');
      return;
    }

    ElMessageBox.confirm('确认要删除该分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let category = {
        id: data.id,
        name: data.name
      };
      var url = "api/toolcategory/delete";
      axios.post(url, category).then(res => {
        console.log(res.data);
        if("success" === res.data.status){
            //initDatas(res.data);
            const parent = node.parent;
            if(parent.level > 0){
              const children = parent.data.children || parent.data;
              const index = children.findIndex(d => d.id === data.id);
              children.splice(index, 1);
            }else{
              const index = CategoryList.findIndex(d => d.id === data.id);
              CategoryList.splice(index,1);
              treeKey.value++;
            }
        }else{
          ElMessage(res.data.message);
          return;
        }
      }).catch(function (error) {
        ElMessage('删除分类出错:'+error);
        return;
      })
    }).catch(() => {
      // 用户点击取消
      console.log('用户点击了取消');
    });
  }
  
}
 
// 编辑
function edit(data) {
  if(checkLogin()){
    if("system" === data.userid){
      ElMessage('系统预置分类，不允许编辑');
      return;
    }
    if(data.userid !== store.state.uid){
      ElMessage('非本账户创建的分类，不允许编辑');
      return;
    }
    ElMessageBox.prompt('请输入标题', '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(({ value }) => {
        if (value != null) {
            let category = {
                id: data.id,
                name: value,
                title: value
            };

            var url = "api/toolcategory/update";
            axios.post(url, category).then(res => {
              console.log(res.data);
              if("success" === res.data.status){
                  //initDatas(res.data);
                  data.title = value;
                  data.name = value;
              }else{
                ElMessage(res.data.message);
                return;
              }
            }).catch(function (error) {
              ElMessage('修改分类出错:'+error);
              return;
            })
        }
    }).catch(() => { });
  }
  
}

defineExpose({
  drawerVisible,
  parentModule,
  initAllCategory,
  disType,
  setPreCheckedNodeArr
});
</script>

<style>
.el-aside {
  background-color: #D3DCE6;
  color: #D3DCE6;
  text-align: center;
  line-height: 20px;
  padding: 0px !important;
}

.el-main {
  background-color: #f4f5f7;
  color: #f4f5f7;
  text-align: left;
  line-height: 20px;
  padding: 0px !important;
}

.scrollDiv {
  overflow-y: scroll;
  height: 470px;
}

.classbutton{
  position: relative;
  height: 33px;
  width: 100px;
  background: rgba(35, 19, 252, 0.425);
  border-radius: 10px;
  box-shadow: none;
  color: white;
  margin-left: 40px;
  margin-right: 10px;
}
</style>